<?php


namespace app\admin\controller;
require_once ROOT_PATH . DS . 'spout-3.1.0/src/Spout/Autoloader/autoload.php';

use Box\Spout\Reader\Common\Creator\ReaderEntityFactory;


class Zhibo extends Base
{
    public function __construct()
    {
        parent::__construct();
    }

    public function type()
    {

        $list = n2db('zhibo_type')->order('sort', 'asc')->select();
        $this->assign('list', $list);
        return $this->fetch('admin@zhibo/type');
    }

    public function field()
    {
        $param = input();
        $ids = $param['ids'];
        $col = $param['col'];
        $val = $param['val'];
        $tab = $param['tab'];

        if (!empty($ids) && $col === 'sort') {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = n2db($tab)->where($where)->setField('sort', $val);
            if ($return !== false) {
                if ($tab == 'zhibo_sort_import') {
                    $zsiInfo = n2db($tab)->where('id', $ids)->find();
                    n2db('zhibo_sort')->where('import_name', $zsiInfo['name'])->update(['sort' => $val]);
                }
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        } elseif (!empty($ids) && $col === 'alias_name') {
            $where = [];
            $where['id'] = ['in', $ids];
            $return = n2db($tab)->where($where)->setField('alias_name', $val);
            if ($return!==false) {
                return $this->success('操作成功');
            } else {
                return $this->error('操作失败');
            }
        }
        return $this->error('参数错误');
    }

    public function changeshow()
    {
        $id = input('id');
        $setState = input('setState');
        if (empty($id)) {
            $this->error('数据出错了');
        }
        if ($setState != 1) {
            $setState = 0;
        } else {
            $setState = 1;
        }

        $update = n2db('zhibo_type')->where('id', $id)->setField('is_show', $setState);
        if ($update) {
            $this->success('设置成功');
        } else {
            $this->error('设置失败！');
        }

    }

    public function sort()
    {
        $typeId = input('type_id', 0, 'intval');
        if (empty($typeId) || $typeId < 1) {
            $this->error('数据有误！');
        }
        $typeInfo = n2db('zhibo_type')->where('id', $typeId)->find();
        if (empty($typeInfo)) {
            $this->error('数据有误！');
        }
        $import = input('import', 0);
        if (!empty($import)) {
            $import = true;
        } else {
            $import = false;
        }

        $sortArray = n2db('zhibo_sort_import')->alias('zsi')->join('zhibo_sort zs', 'zs.import_name=zsi.name', 'left')->order('zsi.sort', 'asc')->where('zsi.type_id', $typeId)->field('zsi.sort as sort,zsi.name as name,zsi.id as id,zs.id as game_id,zs.raw_name as game_name')->select();
//        dump(db('zhibo_sort_import')->getLastSql());


        $this->assign('sortArray', $sortArray);
        if (empty(array_filter($sortArray))) {
            $import = false;
        } else {
            $import = true;
        }
        n2db('zhibo_sort')->where('sort', '<', 1)->update(['sort' => 999]);
        $games = n2db('zhibo_sort')->where('type_id', $typeId)->where('sort', 999)->select();

        $this->assign('games', $games);
        $this->assign('import', $import);
        $this->assign('typeInfo', $typeInfo);

        $this->assign('param', ['type_id' => $typeId]);

        return $this->fetch('admin@zhibo/sort');

    }

    public function uploadExcel()
    {
        set_time_limit(0);
        $typeId = input('type_id', 0, 'intval');
        if ($typeId < 41) {
            $this->error('分类信息有误！');
        }

        $file = request()->file('file');
        if ($file) {
            $path = ROOT_PATH . DS . 'upload/excel';
            if (!file_exists($path)) {
                mkdir($path, 0777, true);
            }
            $info = $file->move($path);
            if ($info) {
                $fileExtension = $info->getExtension();
                $filePath = $path . DS . ($info->getSaveName());
                if ($fileExtension !== 'xlsx') {
                    unlink($filePath);
                    $this->error('文件类型错误！');
                }
                $reader = ReaderEntityFactory::createXLSXReader();
                $reader->open($filePath);
                $i = 1;
                $cells = [];
//                db('zhibo_sort_import')->where('id', '>', 0)->update(['sort' => 999]);

                foreach ($reader->getSheetIterator() as $sheet) {
                    foreach ($sheet->getRowIterator() as $index => $row) {
                        if ($index > 1) {
                            // do stuff with the row
                            $rawdata = $row->getCells();
//                            $cells[$index] = trim($rawdata[0]);
                            $rawdata = trim($rawdata[0]);
                            if (!empty($rawdata)) {
                                $cells = [
                                    'sort' => $i,
                                    'type_id' => $typeId,
                                    'name' => $rawdata,
                                ];
                                $i++;

                                //如果有则更新 没有则插入
                                $isExsitNameInfo = n2db('zhibo_sort_import')->where('name', $cells['name'])->where('type_id', $typeId)->find();
                                if (empty($isExsitNameInfo)) {
                                    n2db('zhibo_sort_import')->insertGetId($cells);
                                } else {
                                    n2db('zhibo_sort_import')->where('id', $isExsitNameInfo['id'])->update([
                                        'sort' => $cells['sort'],
                                    ]);
                                }
                            }
                        }
                    }
                }
                $reader->close();
                $this->success('上传成功，请进行关联！');
            } else {
                // 上传失败获取错误信息
//                echo $file->getError();
                $this->error($file->getError());
            }
        } else {
            $this->error('上传出错！');
        }
    }

    public function bindnamesort()
    {
        $typeId = input('type_id', 0, 'intval');
        if ($typeId < 41) {
            $this->error('分类信息有误！');
        }
        $nameId = input('name_id', 0, 'intval');
        $nameInfo = n2db('zhibo_sort_import')->where('id', $nameId)->find();
        if (empty($nameInfo)) {
            $this->error('排序信息有误！');
        }

        $gameId = input('game_id', 0, 'intval');
        $gameInfo = n2db('zhibo_sort')->where('id', $gameId)->find();
        if (empty($gameInfo)) {
            $this->error('请选择一个比赛名称');
        }

        //处理所有排序为0的改为999
        n2db('zhibo_sort')->where('type_id', $typeId)->where('sort', '<', 1)->update(['sort' => 999]);
        //移除原来的绑定关系
        n2db('zhibo_sort')->where('id', $gameId)->update([
            'import_name' => $nameInfo['name'],
            'sort' => $nameInfo['sort']
        ]);


        $this->success('操作成功!');


    }

    public function unbindNameSort()
    {
        $nameId = input('name_id', 0, 'intval');
        $nameInfo = n2db('zhibo_sort_import')->where('id', $nameId)->find();
        if (empty($nameInfo)) {
            $this->error('排序信息有误！');
        }

        $gameId = input('game_id', 0, 'intval');
        $gameInfo = n2db('zhibo_sort')->where('id', $gameId)->find();
        if (empty($gameInfo)) {
            $this->error('请选择一个比赛名称');
        }
        n2db('zhibo_sort')->where('id', $gameId)->update(['sort' => 999, 'import_name' => '']);
        $this->success('操作成功!');


    }

    public function deleteNameSort()
    {
        $nameId = input('name_id', 0, 'intval');
        $nameInfo = n2db('zhibo_sort_import')->where('id', $nameId)->find();
        if (empty($nameInfo)) {
            $this->error('排序信息有误！');
        }

        $gameInfo = n2db('zhibo_sort')->where('import_name', $nameInfo['name'])->find();
        if (!empty($gameInfo)) {
            n2db('zhibo_sort')->where('id', $gameInfo['id'])->update(['sort' => 999, 'import_name' => '']);
        }

        n2db('zhibo_sort_import')->where('id', $nameId)->delete();
        $this->success('操作成功！');
    }


    public function data()
    {
        $typeId = input('type_id', 0, 'intval');
        $typeInfo = n2db('zhibo_type')->where('id', $typeId)->find();
        if (empty($typeInfo)) {
            $this->error('数据有误！');
        }
        $param = input();
        $where = [];
        $limit = intval($param['limit']) < 1 ? $this->_pagesize : $param['limit'];
        $keyword = trim($param['keyword']);
        if (!empty($keyword)) {
            $where['z.zhibo_name|z.zhibo_qiudui|zs.import_name'] = ['like', '%' . $keyword . '%'];
        }
        $zhiboTime = strtotime(date('Y-m-d', strtotime('tomorrow')) . ' +1 day');
        //得到所有的视频直播
        $list = n2db('zhibo')->alias('z')
            ->join('zhibo_sort zs', 'zs.raw_name = z.zhibo_name and zs.type_id = z.type_id', 'LEFT')
            ->join('ad a', 'a.zhibo_id=z.zhibo_id', 'LEFT')
            ->fieldRaw('z.*,zs.import_name as alias_name,from_unixtime(z.zhibo_time) as datetime,a.adtype,a.from,a.id as ad_id')
            ->where('z.type_id', $typeId)
//            ->whereTime('z.zhibo_time','<',$zhiboTime)
//            ->where('z.zhibo_status', '<>', 3)
            ->where($where)->orderRaw('from_unixtime(z.zhibo_time,"%Y-%m-%d") asc,z.zhibo_time asc')->paginate($limit);
//        dump(db('zhibo')->getLastSql());

        $this->assign('list', $list->items());
        $this->assign('total', $list->total());
        $this->assign('page', $list->currentPage());
        $this->assign('limit', $list->listRows());
        $this->assign('typeInfo', $typeInfo);
        $param = input();
        $param['page'] = '{page}';
        $param['limit'] = '{limit}';
        $this->assign('keyword', $keyword);
        $this->assign('param', $param);
        return $this->fetch('admin@zhibo/vodindex');
    }

    public function changeTop()
    {
        $type = input('type', '', 'trim');
        $status = input('status', 0, 'intval');
        if (empty($type) || !in_array($type, ['is_top', 'is_homepage'])) {
            $this->error('操作有误！');
        }

        $zhiboId = input('zhibo_id', 0, 'intval');
        $zhiboInfo = n2db('zhibo')->where('zhibo_id', $zhiboId)->find();
        if (empty($zhiboInfo)) {
            $this->error('数据有误！');
        }
        n2db('zhibo')->where('zhibo_id', $zhiboId)->update([
            $type => $status > 0 ? 1 : 0
        ]);
        $this->success('操作成功！');

    }

}